import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag, Switch } from 'tdesign-react';
import { SearchIcon, AddIcon, EditIcon, DeleteIcon, RefreshIcon } from 'tdesign-icons-react';
import { JupiterDictionary, JupiterDictionaryQuery, JupiterDictionaryForm } from '../../types/dictionaryTypes';
import { formatTime } from '../../utils/timeutil';
import {
    fetchDictionaryList,
    createDictionary,
    updateDictionary,
    deleteDictionary,
    fetchDictionariesByType
} from '../../services/dictionaryService';
import DictionaryForm from './components/DictionaryForm';

export default function DictionaryPage() {
    const [dictionaryList, setDictionaryList] = useState<JupiterDictionary[]>([]);
    const [loading, setLoading] = useState(false);
    const [formVisible, setFormVisible] = useState(false);
    const [editingDictionary, setEditingDictionary] = useState<Partial<JupiterDictionary>>();
    const [title, setTitle] = useState('新增字典');

    // 搜索条件
    const [searchDictType, setSearchDictType] = useState('');
    const [searchDictKey, setSearchDictKey] = useState('');
    const [searchDictLabel, setSearchDictLabel] = useState('');

    // 分页
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    // 字典类型选项
    const [dictTypeOptions, setDictTypeOptions] = useState<{ label: string; value: string }[]>([]);

    const getList = async () => {
        setLoading(true);
        try {
            const params: JupiterDictionaryQuery = {
                dictType: searchDictType || undefined,
                dictKey: searchDictKey || undefined,
                dictLabel: searchDictLabel || undefined,
                page: pagination.current,
                size: pagination.pageSize,
            };
            const response = await fetchDictionaryList(params);
            if (response.code === 200) {
                setDictionaryList(response.data.records || []);
                setPagination(prev => ({
                    ...prev,
                    total: response.data.total || 0,
                }));
            }
        } catch (error) {
            MessagePlugin.error('获取字典列表失败');
        } finally {
            setLoading(false);
        }
    };

    const getDictTypeOptions = async () => {
        try {
            const response = await fetchDictionariesByType('dict_type');
            if (response.code === 200) {
                const options = response.data.map((item: JupiterDictionary) => ({
                    label: item.dictLabel,
                    value: item.dictKey,
                }));
                setDictTypeOptions(options);
            }
        } catch (error) {
            console.error('获取字典类型选项失败:', error);
        }
    };

    const handleSearch = () => {
        setPagination(prev => ({ ...prev, current: 1 }));
        getList();
    };

    const handleReset = () => {
        setSearchDictType('');
        setSearchDictKey('');
        setSearchDictLabel('');
        setPagination(prev => ({ ...prev, current: 1 }));
        getList();
    };

    const handleCreate = () => {
        setEditingDictionary({});
        setTitle('新增字典');
        setFormVisible(true);
    };

    const handleEdit = (record: JupiterDictionary) => {
        setEditingDictionary(record);
        setTitle('编辑字典');
        setFormVisible(true);
    };

    const handleDelete = (record: JupiterDictionary) => {
        DialogPlugin.confirm({
            header: '确认删除',
            body: `确定要删除字典项"${record.dictLabel}"吗？`,
            onConfirm: async () => {
                try {
                    const response = await deleteDictionary(record.uuid);
                    if (response.code === 200) {
                        MessagePlugin.success('删除成功');
                        getList();
                    } else {
                        MessagePlugin.error(response.message || '删除失败');
                    }
                } catch (error) {
                    MessagePlugin.error('删除失败');
                }
            },
        });
    };

    const handleFormSubmit = async (formData: JupiterDictionaryForm) => {
        try {
            let response;
            if (editingDictionary?.uuid) {
                response = await updateDictionary(editingDictionary.uuid, formData);
            } else {
                response = await createDictionary(formData);
            }

            if (response.code === 200) {
                MessagePlugin.success(editingDictionary?.uuid ? '更新成功' : '创建成功');
                setFormVisible(false);
                getList();
            } else {
                MessagePlugin.error(response.message || '操作失败');
            }
        } catch (error) {
            MessagePlugin.error('操作失败');
        }
    };

    const handlePageChange = (pageInfo: any) => {
        setPagination(prev => ({
            ...prev,
            current: pageInfo.current,
            pageSize: pageInfo.pageSize,
        }));
    };

    const columns = [
        {
            colKey: 'dictType',
            title: '字典类型',
            width: 120,
        },
        {
            colKey: 'dictKey',
            title: '字典键',
            width: 150,
        },
        {
            colKey: 'dictValue',
            title: '字典值',
            width: 150,
        },
        {
            colKey: 'dictLabel',
            title: '显示标签',
            width: 150,
        },
        {
            colKey: 'sortOrder',
            title: '排序',
            width: 80,
        },
        {
            colKey: 'description',
            title: '描述',
            width: 200,
        },
        {
            colKey: 'createTime',
            title: '创建时间',
            width: 180,
            cell: ({ row }: any) => formatTime(row.createTime),
        },
        {
            colKey: 'operation',
            title: '操作',
            width: 150,
            cell: ({ row }: any) => (
                <div style={{ display: 'flex', gap: 8 }}>
                    <Button
                        theme="primary"
                        variant="text"
                        icon={<EditIcon />}
                        onClick={() => handleEdit(row)}
                    >
                        编辑
                    </Button>
                    <Button
                        theme="danger"
                        variant="text"
                        icon={<DeleteIcon />}
                        onClick={() => handleDelete(row)}
                    >
                        删除
                    </Button>
                </div>
            ),
        },
    ];

    useEffect(() => {
        getList();
        getDictTypeOptions();
    }, [pagination.current, pagination.pageSize]);

    return (
        <Card title="字典管理">
            {/* 搜索区域 */}
            <div style={{ marginBottom: 16, padding: '16px 0', borderBottom: '1px solid #e7e7e7' }}>
                <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                    <Select
                        placeholder="字典类型"
                        value={searchDictType}
                        onChange={(value) => setSearchDictType(value as string)}
                        style={{ width: 200 }}
                        options={dictTypeOptions}
                        clearable
                    />
                    <Input
                        placeholder="字典键"
                        value={searchDictKey}
                        onChange={(value) => setSearchDictKey(value as string)}
                        style={{ width: 200 }}
                    />
                    <Input
                        placeholder="显示标签"
                        value={searchDictLabel}
                        onChange={(value) => setSearchDictLabel(value as string)}
                        style={{ width: 200 }}
                    />
                    <Button theme="primary" icon={<SearchIcon />} onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button theme="default" onClick={handleReset}>
                        重置
                    </Button>
                </div>
            </div>

            {/* 操作按钮 */}
            <div style={{ marginBottom: 16, textAlign: 'right' }}>
                <Button theme="primary" icon={<AddIcon />} onClick={handleCreate}>
                    新增字典
                </Button>
            </div>

            {/* 表格 */}
            <Table
                data={dictionaryList}
                rowKey="uuid"
                columns={columns}
                loading={loading}
                pagination={{
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    total: pagination.total,
                    onChange: handlePageChange,
                }}
            />

            {/* 表单弹窗 */}
            <DictionaryForm
                visible={formVisible}
                title={title}
                editingData={editingDictionary}
                onClose={() => setFormVisible(false)}
                onSubmit={handleFormSubmit}
            />
        </Card>
    );
}
